package com.guomei.controller.exam;

import com.guomei.bean.exam.domain.ExamAnswerDetail;
import com.guomei.bean.exam.domain.ExamUserAnswerVO;
import com.guomei.mapper.curse.ExamQuestionMapper;
import com.guomei.service.exam.ExamAnswerDetailService;
import com.guomei.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 考试答卷详情控制器
 */
@RestController
@RequestMapping("/api1/examAnswerDetail")
@Slf4j
public class ExamAnswerDetailController {
    @Autowired
    private ExamAnswerDetailService examAnswerDetailService;


    /**
     * 获取答卷详情信息
     * @return 答卷详情列表
     */
    @PostMapping("/select")
    public Result<?> getAllAnswerDetails(@RequestBody ExamAnswerDetail examAnswerDetail) {
        log.info("获取答卷详情信息");
        try {
            if (examAnswerDetail == null || examAnswerDetail.getPageNum() == null || examAnswerDetail.getPageSize() == null) {
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (examAnswerDetail.getPageNum() <= 0 || examAnswerDetail.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            return examAnswerDetailService.getByCondition(examAnswerDetail);
        } catch (Exception e) {
            log.info("获取答卷详情信息失败", e);
            return Result.fail("获取答卷详情信息失败");
        }
    }

    /**
     * 根据ID获取答卷详情
     * @param id 答卷详情ID
     * @return 答卷详情
     */
    @GetMapping("/detail/{id}")
    public Result<?> getAnswerDetailById(@PathVariable Long id) {
        log.info("获取答卷详情，ID：{}", id);
        try {
            if (id == null) {
                return Result.fail("答卷详情ID不能为空");
            }
            ExamAnswerDetail examAnswerDetail = examAnswerDetailService.getById(id);
            if (examAnswerDetail == null) {
                return Result.fail("答卷详情记录不存在");
            }
            return Result.success(examAnswerDetail);
        } catch (Exception e) {
            log.info("获取答卷详情失败", e);
            return Result.fail("获取答卷详情失败");
        }
    }

    /**
     * 保存答题记录
     * @param answerId 答卷ID
     * @param questionId 题目ID
     * @param userAnswer 用户答案
     * @return 保存结果
     */
    @PostMapping("/save/{answerId}/{questionId}")
    public Result<?> saveAnswer(@PathVariable Long answerId, @PathVariable Long questionId, 
                               @RequestParam String userAnswer) {
        log.info("保存答题记录，答卷ID：{}，题目ID：{}", answerId, questionId);
        try {
            if (answerId == null) {
                return Result.fail("答卷ID不能为空");
            }
            if (questionId == null) {
                return Result.fail("题目ID不能为空");
            }
            if (userAnswer == null) {
                return Result.fail("用户答案不能为空");
            }
            return examAnswerDetailService.saveAnswer(answerId, questionId, userAnswer);
        } catch (Exception e) {
            log.info("保存答题记录失败", e);
            return Result.fail("保存答题记录失败");
        }
    }

    /**
     * 批量保存答题记录
     * @param answerId 答卷ID
     * @param answerDetails 答题详情列表
     * @return 保存结果
     */
    @PostMapping("/batchSave/{answerId}")
    public Result<?> batchSaveAnswer(@PathVariable Long answerId, @RequestBody List<ExamAnswerDetail> answerDetails) {
        log.info("批量保存答题记录，答卷ID：{}", answerId);
        try {
            if (answerId == null) {
                return Result.fail("答卷ID不能为空");
            }
            if (answerDetails == null || answerDetails.isEmpty()) {
                return Result.fail("答题详情不能为空");
            }
            return examAnswerDetailService.batchSaveAnswer(answerId, answerDetails);
        } catch (Exception e) {
            log.info("批量保存答题记录失败", e);
            return Result.fail("批量保存答题记录失败");
        }
    }

    /**
     * 评分
     * @param answerDetailId 答题详情ID
     * @param score 分数
     * @param reviewRemark 审核备注
     * @return 评分结果
     */
    @PostMapping("/score/{answerDetailId}/{score}")
    public Result<?> scoreAnswer(@PathVariable Long answerDetailId, @PathVariable Integer score, 
                                @RequestParam(required = false) String reviewRemark) {
        log.info("评分，答题详情ID：{}，分数：{}", answerDetailId, score);
        try {
            if (answerDetailId == null) {
                return Result.fail("答题详情ID不能为空");
            }
            if (score == null) {
                return Result.fail("分数不能为空");
            }
            return examAnswerDetailService.scoreAnswer(answerDetailId, score, reviewRemark);
        } catch (Exception e) {
            log.info("评分失败", e);
            return Result.fail("评分失败");
        }
    }

    /**
     * 批量评分
     * @param answerDetails 答题详情列表
     * @return 评分结果
     */
    @PostMapping("/batchScore")
    public Result<?> batchScoreAnswer(@RequestBody List<ExamAnswerDetail> answerDetails) {
        log.info("批量评分");
        try {
            if (answerDetails == null || answerDetails.isEmpty()) {
                return Result.fail("答题详情不能为空");
            }
            return examAnswerDetailService.batchScoreAnswer(answerDetails);
        } catch (Exception e) {
            log.info("批量评分失败", e);
            return Result.fail("批量评分失败");
        }
    }

    /**
     * 根据答卷ID获取答题详情列表
     * @param answerId 答卷ID
     * @return 答题详情列表
     */
    @GetMapping("/answer/{answerId}")
    public Result<?> getAnswerDetailsByAnswerId(@PathVariable Long answerId) {
        log.info("根据答卷ID获取答题详情列表，答卷ID：{}", answerId);
        try {
            if (answerId == null) {
                return Result.fail("答卷ID不能为空");
            }
            List<ExamAnswerDetail> answerDetails = examAnswerDetailService.getByAnswerId(answerId);
            return Result.success(answerDetails);
        } catch (Exception e) {
            log.info("根据答卷ID获取答题详情列表失败", e);
            return Result.fail("获取答题详情列表失败");
        }
    }

    /**
     * 根据题目ID获取答题详情列表
     * @param questionId 题目ID
     * @return 答题详情列表
     */
    @GetMapping("/question/{questionId}")
    public Result<?> getAnswerDetailsByQuestionId(@PathVariable Long questionId) {
        log.info("根据题目ID获取答题详情列表，题目ID：{}", questionId);
        try {
            if (questionId == null) {
                return Result.fail("题目ID不能为空");
            }
            List<ExamAnswerDetail> answerDetails = examAnswerDetailService.getByQuestionId(questionId);
            return Result.success(answerDetails);
        } catch (Exception e) {
            log.info("根据题目ID获取答题详情列表失败", e);
            return Result.fail("获取答题详情列表失败");
        }
    }

    /**
     * 根据答卷ID和题目ID获取答题详情
     * @param answerId 答卷ID
     * @param questionId 题目ID
     * @return 答题详情
     */
    @GetMapping("/answer/{answerId}/question/{questionId}")
    public Result<?> getAnswerDetailByAnswerIdAndQuestionId(@PathVariable Long answerId, @PathVariable Long questionId) {
        log.info("根据答卷ID和题目ID获取答题详情，答卷ID：{}，题目ID：{}", answerId, questionId);
        try {
            if (answerId == null) {
                return Result.fail("答卷ID不能为空");
            }
            if (questionId == null) {
                return Result.fail("题目ID不能为空");
            }
            ExamAnswerDetail answerDetail = examAnswerDetailService.getByAnswerIdAndQuestionId(answerId, questionId);
            if (answerDetail == null) {
                return Result.fail("答题详情记录不存在");
            }
            return Result.success(answerDetail);
        } catch (Exception e) {
            log.info("根据答卷ID和题目ID获取答题详情失败", e);
            return Result.fail("获取答题详情失败");
        }
    }

    /**
     * 统计答卷详情数量
     * @param answerId 答卷ID
     * @return 详情数量
     */
    @GetMapping("/count/answer/{answerId}")
    public Result<?> countByAnswerId(@PathVariable Long answerId) {
        log.info("统计答卷详情数量，答卷ID：{}", answerId);
        try {
            if (answerId == null) {
                return Result.fail("答卷ID不能为空");
            }
            int count = examAnswerDetailService.countByAnswerId(answerId);
            return Result.success(count);
        } catch (Exception e) {
            log.info("统计答卷详情数量失败", e);
            return Result.fail("统计失败");
        }
    }

    /**
     * 统计题目答题数量
     * @param questionId 题目ID
     * @return 答题数量
     */
    @GetMapping("/count/question/{questionId}")
    public Result<?> countByQuestionId(@PathVariable Long questionId) {
        log.info("统计题目答题数量，题目ID：{}", questionId);
        try {
            if (questionId == null) {
                return Result.fail("题目ID不能为空");
            }
            int count = examAnswerDetailService.countByQuestionId(questionId);
            return Result.success(count);
        } catch (Exception e) {
            log.info("统计题目答题数量失败", e);
            return Result.fail("统计失败");
        }
    }

    /**
     * 计算答卷总分
     * @param answerId 答卷ID
     * @return 总分
     */
    @GetMapping("/score/total/{answerId}")
    public Result<?> sumScoreByAnswerId(@PathVariable Long answerId) {
        log.info("计算答卷总分，答卷ID：{}", answerId);
        try {
            if (answerId == null) {
                return Result.fail("答卷ID不能为空");
            }
            Integer totalScore = examAnswerDetailService.sumScoreByAnswerId(answerId);
            return Result.success(totalScore);
        } catch (Exception e) {
            log.info("计算答卷总分失败", e);
            return Result.fail("计算总分失败");
        }
    }

    /**
     * 关联查询：按答卷ID，返回题目与用户回答及分数
     */
    @GetMapping("/userAnswers/answer/{answerId}")
    public Result<?> getUserAnswersByAnswerId(@PathVariable Long answerId) {
        log.info("关联查询用户回答(按答卷ID)，答卷ID：{}", answerId);
        try {
            if (answerId == null) {
                return Result.fail("答卷ID不能为空");
            }
            List<ExamUserAnswerVO> list = examAnswerDetailService.getUserAnswersByAnswerId(answerId);
            return Result.success(list);
        } catch (Exception e) {
            log.info("关联查询用户回答失败", e);
            return Result.fail("查询失败");
        }
    }

    /**
     * 关联查询：按考试ID与用户ID，返回题目与该用户的回答及分数
     */
    @GetMapping("/userAnswers/exam/{examId}/user/{userId}")
    public Result<?> getUserAnswersByExamIdAndUserId(@PathVariable Long examId, @PathVariable Long userId) {
        log.info("关联查询用户回答(按考试ID与用户ID)，examId：{} userId：{}", examId, userId);
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            if (userId == null) {
                return Result.fail("用户ID不能为空");
            }
            List<ExamUserAnswerVO> list = examAnswerDetailService.getUserAnswersByExamIdAndUserId(examId, userId);
            return Result.success(list);
        } catch (Exception e) {
            log.info("关联查询用户回答失败", e);
            return Result.fail("查询失败");
        }
    }
}
